package com.itheima.controller;

import com.itheima.bean.User;
import com.itheima.dto.UserDTO;
import com.itheima.properties.JwtProperties;
import com.itheima.result.Result;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    //TODO: 完成用户登录功能

    /**
     * 用户登录
     * @param userDTO
     * @return
     */
    @PostMapping("/users/login")
    public Result<UserVo> login(@RequestBody UserDTO userDTO) {
        log.info("用户登录 userDTO = {}",userDTO);
        User user = userService.login(userDTO);
        log.info("用户的id为 {}",user.getId());
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("username",user.getUsername());
        String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claims);
        UserVo userVo = UserVo.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .name(user.getName())
                .token(token)
                .build();
        return Result.success(userVo);
    }
}
